package cn.candy.org.service.impl;

import cn.candy.basic.service.impl.BaseServiceImpl;
import cn.candy.basic.util.MD5Utils;
import cn.candy.basic.util.StrUtils;
import cn.candy.org.domain.Employee;
import cn.candy.org.mapper.EmployeeMapper;
import cn.candy.org.service.IEmployeeService;
import cn.candy.user.domain.Logininfo;
import cn.candy.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 员工业务实现
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void add(Employee employee) {
        //获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        //转成logininfo对象
        Logininfo logininfo = employee2Logininfo(employee);
        //先保存logininfo对象 - 获取自增长的id
        logininfoMapper.save(logininfo);

        //设置logininfo_id
        employee.setLogininfo_id(logininfo.getId()); //直接用字段
        //保存管理员信息
        super.add(employee);
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0); //0表示管理员
        return logininfo;
    }

    @Override
    @Transactional
    public void del(Long employee_id) {
        //通过id获取到管理员对象
        Employee employee = employeeMapper.loadById(employee_id);
        Long logininfo_id = employee.getLogininfo_id();
        //根据logininfo_id删除Logininfo对象
        logininfoMapper.remove(logininfo_id);
        //删除Employee对象
        super.del(employee_id);
    }

    @Override  //@TODO
    @Transactional
    public void update(Employee employee) {//由于是修改  employee有employee_id
        //修改操作 - 密码是新的明文 - 需要重新加密，重新生成
        String salt = StrUtils.getComplexRandomString(32);
        String newMd5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(newMd5Pwd);

        //将employee转成Logininfo对象
        Logininfo logininfo = employee2Logininfo(employee);
        //修改操作 - 根据id修改【需要设置logininfo以前的id】
        //通过employee_id查询employee对象
        Employee dbEmployee = employeeMapper.loadById(employee.getId());
        //将logininfo对象以前的id设置回去
        logininfo.setId(dbEmployee.getLogininfo_id());
        //根据id修改
        logininfoMapper.update(logininfo);

        super.update(employee);
    }
}
